#include "widget.h"
#include "ui_widget.h"
#include <QVBoxLayout>
#include <QTranslator>
#include <QApplication>
#include <QDebug>

Widget::Widget(QApplication *a, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    app = a;
    qDebug() << parent;

    ui->setupUi(this);
    createScreen();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::createScreen()
{
    combo = new QComboBox;
    combo->addItem("English", "en");
    combo->addItem("Chinese", "zh");
    combo->addItem("Latin", "la");

    label = new QLabel;

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(combo, 1);
    layout->addWidget(label, 5);

    setLayout(layout);

    connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(changeLang(int)));

    QString langCode = combo->itemData(0).toString(); // ISO标准中语言的简写
    changeTr(langCode);
    refreshLabel();
}

void Widget::refreshLabel()
{
    label->setText(tr("TXT_HELLO_WORLD", "hello world")); // tr的第一个参数是提取翻译串时用到的id，第二个参数是注释。如果在qm文件中找不到id对应的目标串，则使用注释
}

void Widget::changeLang(int index)
{
    QString langCode = combo->itemData(index).toString(); // ISO标准中语言的简写
    changeTr(langCode);
    refreshLabel();
}

void Widget::changeTr(const QString &langCode)
{
    // 读取qm文件，安装translator
    static QTranslator *translator;
    if (translator != nullptr)
    {
        app->removeTranslator(translator);
        delete translator;
        translator = nullptr;
    }

    translator = new QTranslator;
    QString qmFile = "lang_" + langCode + ".qm";

    if (translator->load(qmFile))
    {
        app->installTranslator(translator);
    }
}
